package com.yangxinxin.lesson.service.implement;

import com.yangxinxin.lesson.constant.Constant;
import com.yangxinxin.lesson.entity.SysUser;
import com.yangxinxin.lesson.exception.BusinessException;
import com.yangxinxin.lesson.mapper.SysUserMapper;
import com.yangxinxin.lesson.service.RedisService;
import com.yangxinxin.lesson.service.UserService;
import com.yangxinxin.lesson.utils.PasswordUtils;
import com.yangxinxin.lesson.vo.RequestVo.LoginReqVo;
import com.yangxinxin.lesson.vo.RequestVo.RegistReqVo;
import com.yangxinxin.lesson.vo.RespondVo.LoginRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** @Author yangxinxin
 * @Description //TODO
 * @Date 16:45 2020/2/21
 * @Param 
 * @return 
 **/
@Service
public class UserServiceImpl  implements UserService {
    //拿到dao层的实例
    @Autowired
    private  SysUserMapper sysUserMapper;

    //引入Redis工具类
    @Autowired
    private RedisService redisService;

    @Override
    public LoginRespVo login(LoginReqVo vo) {
        SysUser sysUser  = sysUserMapper.selectByUsername(vo.getUsername());//查找用户名
        if (sysUser==null){
            throw new BusinessException(4001005,"不存在该用户！请先注册！");
        }
        if (sysUser.getStatus()==2){
            throw  new BusinessException(4001006,"该账号已被禁用,请检查该账号状态或重新登陆！请联系系统管理员！");
        }
        if(!PasswordUtils.matches(sysUser.getSalt(),vo.getPassword(),sysUser.getPassword())){
            throw new BusinessException(4001007,"用户名密码不匹配");
        }
/***************利用UUID生成token***************/
        String token = UUID.randomUUID().toString();
        LoginRespVo respVo = new LoginRespVo();
        respVo.setUserId(sysUser.getId()); 
        respVo.setToken(token);
        //将key 和 value 保存到redis中
        redisService.set(token,sysUser.getId(),60, TimeUnit.MINUTES);
        /*标记token把token存入redis,key为UserId,value就是token过期时间和key为token的过期时间一致*/
        redisService.set(sysUser.getId(),token,60,TimeUnit.MINUTES);
        /*KEY     VALUE           时间        指定时间格式*/
        return  respVo;
    }

    @Override
    public SysUser getUserInfo(String id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public String register(RegistReqVo vo) {
        //1.判断验证码是否有效，判断KEY是否存在
        if (!redisService.hasKey(Constant.REGISTER_CODE_COUNT_VALIDITY_KEY+vo.getPhone())){
            throw  new BusinessException(4001008,"验证码已经失效，请重新获取！");
        }
        //2.验证校验码是否正确
        if (!vo.getCode().equals(redisService.get(Constant.REGISTER_CODE_COUNT_VALIDITY_KEY+vo.getPhone()))){
            throw  new BusinessException(4001009,"验证码不正确，请重新输入正确的验证码！");
        }
        SysUser sysUser = sysUserMapper.selectByUsername(vo.getUsername());
        if (sysUser != null){
            throw  new BusinessException(40010010,"用户已经注册，无需注册！");
        }
        SysUser user  = new SysUser();
        BeanUtils.copyProperties(vo,user);//复制用户属性,才能匹配
        user.setId(UUID.randomUUID().toString());
        user.setCreateTime(new Date());

        //密码为密文，首先生成一个加密的盐值
        String salt   = PasswordUtils.getSalt();
        String ecdPwd = PasswordUtils.encode(vo.getPassword(),salt);
        user.setSalt(salt);
        user.setPassword(ecdPwd);
        int i = sysUserMapper.insertSelective(user);//插入数据库
        if (i !=  1){
            throw  new BusinessException(4001011,"操作失败！");
        }
      //  redisService.delete(Constant.REGISTER_CODE_COUNT_VALIDITY_KEY+vo.getPhone());
      //  redisService.delete(Constant.REGISTER_CODE_COUNT_KEY+vo.getPhone());
        return "恭喜您，注册成功！";
    }
    @Override
    public String getCode(String phone) {
        //验证手机号是否合法
        Pattern pattern = Pattern.compile("^1(3|4|5|7|8)\\d{9}$");
        Matcher matcher = pattern.matcher(phone);
        if(!matcher.matches()) {
            throw  new BusinessException(4001004,"手机号格式错误");
        }
        //判断手机号是否超过限制
        long count = redisService.incrby(Constant.REGISTER_CODE_COUNT_KEY+phone,1);
        if (count > 5) {
            throw  new BusinessException(4001004,"当日发送已达上限，请稍后注册！");
        }
        //生成六位验证码
        String code = generateCode();
        //发送短信
        //存入redis过期时间为5min
        redisService.set(Constant.REGISTER_CODE_COUNT_VALIDITY_KEY+phone,code,5, TimeUnit.MINUTES);
        //发送短信，这里模拟输出到控制台上
        System.out.println(code);
        return code;
    }
   /*生成六位验证码*/
    private  String generateCode(){
        Random random =  new Random();
        int     x     =  random.nextInt(899999);
        String code   =  String.valueOf(x + 100000);
        return  code;
    }
}
